<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Main extends CI_Controller {

/**
 * 项目：工程现场管理系统
 *
 * 公司：红河移动分公司
 *
 * @author 李朝应
 *
 * E-mail:lichaoying.hh@163.com
 * Version:V1.0_beta1
 *
 */
     function __construct() {   //构造函数
        parent::__construct();
        $this->load->model('menu_model');
        $this->load->model('setting_model');
        $this->load->model('flow_model');
        $this->load->model('branch_model');
        $this->load->model('members_model');
        $this->load->model('event_model');
        $this->load->model('project_model');
        $this->load->model('flowinfo_model');
        $this->load->model('req_model');
        $this->load->model('proc_model');
        $this->load->model('relpro_model');
       // $this->output->enable_profiler(TRUE);//激活分析器
    }
     private function SQLsafe( $string ) {   //阻止SQL注入式攻击,只适用PHP5
        return "'" . mysql_real_escape_string( $string ) . "'";
    }
    private function SQLsafe2( $string ) {   //阻止SQL注入式攻击,只适用PHP5
        return  mysql_real_escape_string( $string );
    }
    private function parm_0() {  //页面设置参数
        $data['title'] = $this->setting_model->getSetting('PS_title');
        $data['version'] = $this->setting_model->getSetting('PS_version');    
        $data['copyright'] = $this->setting_model->getSetting('copyright');
        $data['system_os'] = PHP_OS;
        $this->load->vars($data);
    }
     private function parm_1() {  //页面设置参数
        $data['title'] = $this->setting_model->getSetting('PS_title');
        $data['version'] = $this->setting_model->getSetting('PS_version');
        $data['sum1'] = 0;//待办工单数量
        $data['sum2'] = 1;//草稿工单数量
        $login=$this->SQLsafe2($this->security->xss_clean($this->session->userdata('psms_username_auth_main')));
        $data['Loginname'] = $this->members_model->getUserNameById($login);       
        $data['copyright'] = $this->setting_model->getSetting('copyright');
        $data['system_os'] = PHP_OS;
        $this->load->vars($data);
    }
    function index(){        
            $this->isOnLine();
            $this->parm_1();
	    $this->load->view('index');
	}
  /*  function menu(){
           $this->parm_1();
           $data['menu'] = $this->menu_model->getNode(0);
           $this->load->view('index', $data);
        }
   */
    function login(){
         if($this->isLogin()){
           $this->event_model->setEventMainOfNoLogin("!!直接登录主页跳转事件","main/login",FALSE);
           $this->parm_0();
           $this->load->view('index');
       }else{
        $this->parm_0();
        $this->load->view('login'); 
        }
    }
  function  checkLogin() {
    //取得表单数量
       $error="";
       $user=$this->SQLsafe2($this->security->xss_clean($this->input->post("username")));
       $pwd=$this->SQLsafe2($this->security->xss_clean($this->input->post("password")));
       if($user==""or $pwd==""){ 
           $this->event_model->setEventMainOfNoLogin("!!!PS非法登录","main/checklogin",FALSE);
           $this->parm_0();
           $msg['error'] ="<span style='color:red'>&nbsp;&nbsp;非法登录错误！</span>";
           $this->load->view("login",$msg);    
       }else{        
         if($this->members_model->isSysytemUser($user,$pwd)){
              $session_data = array('psms_username_auth_main'=>$user,'psms_userpwd_auth_main'=>$pwd); //写入到Session
	      $this->session->set_userdata($session_data);
              $this->members_model->setLastLoginInfo($user,$pwd);
              $this->event_model->setEventMain("用户'".$user."'PS登录成功","main/checklogin",FALSE);
              redirect("main/index");
           }else{
              $this->event_model->setEventMainOfNoLogin("输入用户'".$user."'验证错误","main/checklogin",FALSE);
              $this->parm_0();
              $msg['error'] ="<span style='color:red'>&nbsp;&nbsp;对不起，用户名和密码验证错误！</span>";
              $this->load->view("login",$msg); 
          }      
        }   
      }
  private function isLogin(){//登录判断
    $user=$this->SQLsafe2($this->security->xss_clean($this->session->userdata('psms_username_auth_main')));
    $pwd=$this->SQLsafe2($this->security->xss_clean($this->session->userdata('psms_userpwd_auth_main')));
   if($user==""or $pwd==""){ 
      return FALSE;   
   }else{
      if($this->members_model->isSysytemUser($user,$pwd)){ return TRUE; }else{return FALSE; }
   }
 }
 private function isOnLine(){
     if(!$this->isLogin()){
            $this->event_model->setEventMainOfNoLogin("!!!PS未登录跳转事件","main/isOnLine",FALSE);
            redirect("main/login");;
       }else{
           return TRUE;
       }  
 }
 function logout(){
 if($this->isLogin()){
     $this->event_model->setEventMain("PS用户注销成功","main/logout",FALSE);
     $this->parm_1();
     $this->session->unset_userdata('psms_username_auth_main');
     $this->session->unset_userdata('psms_username_auth_main');
     //$this->session->sess_destroy();  
  }
     redirect("main/login");;        
}      
    function error_404(){
           $this->isOnLine();
           $this->parm_1();
           $this->load->view('error_404');
    }
    function upload(){
      $this->isOnLine();
      $this->load->view('upload');
    }
    function caogao(){
       $this->isOnLine();
       $this->parm_1();
       $this->load->view('blank');    
    }
   function myyiban(){
       $this->isOnLine();
       $this->parm_1();
       $this->load->view('blank');    
    }
    function sys_noguidang(){
       $this->isOnLine();
       $this->parm_1();
       $this->load->view('blank');    
    }
     function sys_guidang(){
       $this->isOnLine();
       $this->parm_1();
       $this->load->view('blank');    
    }
      function myinfo(){
       $this->isOnLine();
       $this->parm_1();
       $this->load->view('blank');    
    }
      function editpw(){
       $this->isOnLine();
       $this->parm_1();
       $this->load->view('blank');    
    }
      function mysetting(){
       $this->isOnLine();
       $this->parm_1();
       $this->load->view('blank');    
    }
       function  users(){
       $this->isOnLine();
       $this->parm_1();
       $this->load->view('blank');    
    }
 
     function sys_allWork(){
       $this->isOnLine();
       $this->parm_1();
       $this->load->view('blank');    
    }
    function myguidang(){
       $this->isOnLine();
       $this->parm_1();
       $this->load->view('blank');    
    }
    function auth_error(){
       $this->isOnLine();
       $this->parm_1();
       $this->load->view('auth_error');     
    }
    function blank(){
        $this->isOnLine();
        $this->parm_1();
        $this->load->view('blank');  
    }
   function mydaiban(){
     $this->isOnLine();
     $this->parm_1();
     $this->load->view('blank');    
   }
   function addPcode(){
     $this->isOnLine();
     $this->parm_1();
     $this->load->view('subwin/addPcode');       
   }
    function addPcode_rst(){
       $this->isOnLine();
       $this->parm_1();
       $pcode=trim($this->input->post('pcode'));
       $name=trim($this->input->post('name'));
       $pm=trim($this->input->post('pm'));
       $years=trim($this->input->post('years'));
       $state=trim($this->input->post('RadioGroup1'));
       $data['proiect']=$this->project_model->getProiectAllByQuery($pcode,$name,$pm,$years,$state);
       $this->load->view('subwin/addPcode_rst',$data);   
 } 
      function createWorkOrders($flow,$currtflow){
        $this->isOnLine();
        $this->parm_1();
        $login=$this->SQLsafe2($this->security->xss_clean($this->session->userdata('psms_username_auth_main')));
        $data['CFC'] =$flow;//当前流程编码
        $data['CSFC'] =$currtflow;//当前子流编码  
        $data['FSID'] =$this->flow_model->getSubFlowID($currtflow);//当前子流程号   
        $tabconfig="";
        $subflowQuery=$this->flow_model->getSubFlowInfo($currtflow);
        if ($subflowQuery->num_rows() > 0)
       {
          foreach ($subflowQuery->result() as $row) {       
               $tabconfig.="<li><a href='#". $row->tabUrl."'>". $row->tabName."</a></li>";      
             }//endforeach
          }       
       $data['tabconfig'] =$tabconfig;
       switch ($flow) {
           case 1:                 
               $data['Tel'] = $this->members_model->getUserTelById($login);
               $data['Email'] = $this->members_model->getUserEmailById($login);      
               $data['branch'] =$this->branch_model->getbranchs();
               $data['nodes']=$this->branch_model->geNodes();
               $data['brid']=$this->members_model->getBridByUid($login);
               $this->load->view('create1',$data); 
               break;
           case 2:
               $this->load->view('create2',$data); 
               break;
           case 3:
               $this->load->view('create3',$data); 
               break;
       }      
   }
   function set_save_1_1_1(){
       $this->isOnLine();
       $error_msg="";
       $batch=$this->input->post("batch");
       $brid=$this->input->post("brid");
       $rid=$this->input->post("rid"); 
       $prid=$this->input->post("prid");      
       $login=$this->SQLsafe2($this->security->xss_clean($this->session->userdata('psms_username_auth_main')));
       $uid=$this->members_model->getUserIdByLogin($login);
       $fsid=$this->input->post("fsid");
       $prname=$this->input->post("rname");
       $username=$this->input->post("username");
       $tel=$this->input->post("tel");
       $email=$this->input->post("email");
       $fiid=$this->input->post("fiid");   
       $return_array=array();//定义返回的数组
        if ($fiid=="" and $rid=="" and $prid==""): 
         $fiid_insert=$this->flowinfo_model->insert_save_1_1_1($brid,$prname,$fsid,$uid);//增加流程信息记录
         $rid_insert=$this->req_model->insert_save_1_1_1($fiid_insert,$brid,$uid,$username,$tel,$email,$batch,$prname);//增加调单信息记录
         $prid_insert= $this->proc_model->insert_save_1_1_1($fiid_insert,$uid);//增加流程明细信息记录
         $error_msg="新增信息保存成功！";
         $return_array = array(
             "fiid" => $fiid_insert ,
             'rid'=>$rid_insert,
             'prid'=>$prid_insert,
             "msg"=>$error_msg
             ); 
        else: 
          $this->flowinfo_model->update_save_1_1_1($fiid,$brid,$prname);  //更新流程信息记录
          $this->req_model->update_save_1_1_1( $rid,$fiid,$brid,$username,$tel,$email,$batch,$prname);//更新流调单信息记录
          $error_msg="信息更新保存成功！";
             $return_array = array(
             "fiid" => $fiid ,
             'rid'=>$rid,
             'prid'=>$prid,
             "msg"=>$error_msg
             ); 
        endif;
      echo json_encode($return_array);//返回JSON类型的数据
   }
   function set_save_1_1_2($state){
       $this->isOnLine();
       $error_msg="";
       $brid=$this->input->post("brid2");
       $rid=$this->input->post("rid2"); 
       $prid=$this->input->post("prid2");  
       $fiid=$this->input->post("fiid2");
       $pcode=trim($this->input->post("pcode"));
       $ptype=$this->input->post("ptype");
       $sgdw=$this->input->post("sgdw");
       $rcAddr=$this->input->post("rcAddr");
       $xcsg=$this->input->post("xcsg");
       $xcjl=$this->input->post("xcjl");
       $xcsgd=$this->input->post("xcsgd");
       $branchPm=$this->input->post("branchPm");
       $planDate=$this->input->post("date-range-picker");
       $mainProjectContent=$this->input->post("mainProjectContent");
       $mainProjectReady=$this->input->post("mainProjectReady");
       if ($planDate!=""):
           $rcPlanDate=substr($planDate,0,strpos($planDate,"-"));//取得起始日期
           $tcPlanDate=substr($planDate,strpos($planDate,"-")+1,strlen($planDate));//取得结束日期
       endif;
       $sjdw=$this->setting_model->getSetting('PS_sjdw');
       $jldw=$this->setting_model->getSetting('PS_jldw');
       $this->relpro_model->delByRid($rid);//删除项目编码关联的所有项
       //添加项目编码关联的所有项
       if($pcode!=""):
           $pcode2 =substr($pcode,0,strlen($pcode)-1);//按逗号分离字符串,去除最后的逗号
           $arr_pcode=explode(',',$pcode2);//按逗号分离字符串       
           for($i=0;$i<count($arr_pcode);$i++){
               $pc=trim( $arr_pcode[$i]);
               $pid=$this->project_model->getPidByPcode($pc);//查询项目ID
               $this->relpro_model->insertRec($rid,$pid,$pc);//增加到数据库
             } 
       endif;
        //分段处理
       switch ($state) {
         case "S":
           $af=$this->req_model->update_save_1_1_2($rid,$pcode,$ptype,$sgdw,$rcAddr,$xcsg,$xcjl,$xcsgd,$branchPm,$rcPlanDate,$tcPlanDate,$mainProjectContent,$mainProjectReady,$sjdw,$jldw);
           $error_msg=$af."条信息更新保存成功！";
            break;
          case "P":
             $af=$this->req_model->update_save_1_1_2($rid,$pcode,$ptype,$sgdw,$rcAddr,$xcsg,$xcjl,$xcsgd,$branchPm,$rcPlanDate,$tcPlanDate,$mainProjectContent,$mainProjectReady,$sjdw,$jldw);
             $wordNum=$this->req_model->getRiWordNumByBrid($brid)+1;
             $RiWord=$this->branch_model->getRiWordById($brid)."[".$this->branch_model->getYearNow()."]".$wordNum."号";
             if($this->req_model->isNullRiWord($rid)){$this->req_model->updateRiWord($rid,$RiWord);}
             $error_msg=$af."条信息更新保存成功！";
              break;
          case "N":
             $af=$this->req_model->update_save_1_1_2($rid,$pcode,$ptype,$sgdw,$rcAddr,$xcsg,$xcjl,$xcsgd,$branchPm,$rcPlanDate,$tcPlanDate,$mainProjectContent,$mainProjectReady,$sjdw,$jldw);
             $wordNum=$this->req_model->getRiWordNumByBrid($brid)+1;
             $RiWord=$this->branch_model->getRiWordById($brid)."[".$this->branch_model->getYearNow()."]".$wordNum."号";
             if($this->req_model->isNullRiWord($rid)){$this->req_model->updateRiWord($rid,$RiWord);}
             $error_msg=$af."条信息更新保存成功！";
             break;
       }
        $return_array = array(
             "fiid" => $fiid ,
             'rid'=>$rid,
             'prid'=>$prid,
             "msg"=>$error_msg
             ); 
     echo json_encode($return_array);//返回JSON类型的数据   
   }
   function exportToExcel($rid){
        $obj=$this->req_model->getRiReqByRid($rid);
        $this->load->library('PHPExcel');       
        $objExcel =PHPExcel_IOFactory::createReader("Excel5")->load($this->setting_model->getSetting('PS_website')."excel/ri.xls"); //设定LOAD的文件PATH,格式为e:/website/psms/*.xls
        $objWriter = new PHPExcel_Writer_Excel5($objExcel);  
        $objExcel->setActiveSheetIndex(0);//缺省情况下，PHPExcel会自动创建第一个sheet被设置SheetIndex=0
        $objActSheet = $objExcel->getActiveSheet();
        //设置文档基本属性
        $objProps = $objExcel->getProperties();
        $objProps->setCreator("Chaoying Li");
        $objProps->setLastModifiedBy("PSMS");
        $objProps->setTitle("PSMS");
        $objProps->setSubject("Chaoying Li");
        $objProps->setDescription("Office Excel By China Mobile co.,ltd.");
        //设置当前活动sheet的名称
        $objActSheet->setTitle("工程入场申请");       
        //设置单元格内容
        $objActSheet->setCellValue('B2',$obj->riWord); 
        $objActSheet->setCellValue('E2',"第".$obj->batch."批次");   
        $pcode=$obj->pcode;
        $pcode2 =substr($pcode,0,strlen($pcode)-1);//按逗号分离字符串,去除最后的逗号
        $arr_pcode=explode(',',$pcode2);//按逗号分离字符串   
        if(count($arr_pcode)>1):
          $arry_1=str_replace("中国移动云南公司","",$this->project_model->getPnameWithPcodeAuth($arr_pcode[0]))."等";//取第一项的结果     
        else:
          $arry_1=str_replace("中国移动云南公司","",$this->project_model->getPnameWithPcodeAuth($arr_pcode[0]));//取第一项的结果        
        endif;
        $objActSheet->setCellValue('B4',$arry_1);//工程名称
        $objActSheet->setCellValue('E4',$obj->prname); 
        $objActSheet->setCellValue('B5',$obj->pcode); 
        $objActSheet->setCellValue('E5',$obj->ptype);        
        $objActSheet->setCellValue('B6',$this->branch_model->getBrnamebyID($obj->brid)); //县市
        $objActSheet->setCellValue('E6',$obj->sjdw); 
        $objActSheet->setCellValue('B7',$obj->jldw); 
        $objActSheet->setCellValue('E7',$obj->sgdw); 
        $objActSheet->setCellValue('B8',$obj->rcPlanDate); 
        $objActSheet->setCellValue('E8',$obj->tcPlanDate); 
        $objActSheet->setCellValue('B9',$obj->rcAddr);
        $objActSheet->setCellValue('B10',$obj->xcsg);
        $objActSheet->setCellValue('E10',$obj->branchPm);
        $objActSheet->setCellValue('B11',$obj->xcjl);
        $objActSheet->setCellValue('E11',$obj->xcsgd);
        $objActSheet->setCellValue('B12',$obj->mainProjectContent);
        $objActSheet->setCellValue('B13',$obj->mainProjectReady);
        $rcPlanDate=$obj->rcPlanDate;
        $planText="本工程计划于".$rcPlanDate."正式入场，特此报告。\n\n  主送：工程建设中心、".$obj->jldw."；\n  抄送：网络部；";
        $objActSheet->setCellValue('A14',$planText);
        //输出内容
        if($obj->riWord==""):
           $outputFileName = $this->branch_model->getBrnamebyID($obj->brid)."工程入场申请".".xls";
        else:
            $outputFileName = $this->branch_model->getBrnamebyID($obj->brid)."工程入场申请(".$obj->riWord.").xls";  
        endif;
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="'.$outputFileName.'"');
        header("Content-Transfer-Encoding: binary");
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");
        $objWriter->save('php://output');
   }
    function set_upload(){           
        // HTTP headers for no cache etc 头部没有缓存
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");
        //上传路径      
        $targetDir = 'uploads/';
        //创建文件夹
        date_default_timezone_set('PRC');//把时间调到北京时间
	$ymd = date("Ymd");
	$targetDir .= $ymd . "/";
	if (!file_exists($targetDir)) {
		mkdir($targetDir);
                copy("uploads/index.html", $targetDir."index.html");
                @chmod($targetDir."index.html", 0644);//修改目录权限(Linux)
	}
       //echo $targetDir; //debug
        // 脚本执行时间
        @set_time_limit(5 * 60);
        // 延迟
        // usleep(5000);

        // 接收 pluploa的参数
        $chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0;
        $chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0;
        $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';
        $prid=$this->input->post("prid");  
        $type=$this->input->post("type");
        $oldFileName=$this->input->post("oldFileName");
        $fileSize=$this->input->post("fileSize");//字节数
        // 文件名整理
        $fileName = preg_replace('/[^\w\._]+/', '', $fileName);
        // 这里主要是如果JS参数设置了唯一文件名，则进行唯一文件名的处理，chunks<2 的意思是只有在不分块上传的情况下才会进行唯一文件名。否则将和分块上传的原理冲突，第1块以后的文件流将无法写入正确的文件中。
        if ($chunks < 2 && file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName)) {
          $ext = strrpos($fileName, '.');
          $fileName_a = substr($fileName, 0, $ext);
          $fileName_b = substr($fileName, $ext);
          $count = 1;
         while (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b))
           $count++;
         $fileName = $fileName_a . '_' . $count . $fileName_b;
        }
        if (is_dir($targetDir) && ($dir = opendir($targetDir))) {
         while (($file = readdir($dir)) !== false) {
          $filePath = $targetDir . DIRECTORY_SEPARATOR . $file;
          // Remove temp files if they are older than the max age
          if (preg_match('/\\.tmp$/', $file) && (filemtime($filePath) < time() - $maxFileAge))
           @unlink($filePath);
         }

         closedir($dir);
        } else
         die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');

        // 上传写文件步骤,这一部分以下的代码可直接引用
        if (isset($_SERVER["HTTP_CONTENT_TYPE"]))
         $contentType = $_SERVER["HTTP_CONTENT_TYPE"];

        if (isset($_SERVER["CONTENT_TYPE"]))
         $contentType = $_SERVER["CONTENT_TYPE"];

        // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
        if (strpos($contentType, "multipart") !== false) {
         if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
          // Open temp file
          $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
          if ($out) {
           // Read binary input stream and append it to temp file
           $in = fopen($_FILES['file']['tmp_name'], "rb");

           if ($in) {
            while ($buff = fread($in, 4096))
             fwrite($out, $buff);
           } else
            die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
           fclose($in);
           fclose($out);
           @unlink($_FILES['file']['tmp_name']);
          } else
           die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
         } else
          die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
        } else {
         // Open temp file
         $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
         if ($out) {
          // Read binary input stream and append it to temp file
          $in = fopen("php://input", "rb");

          if ($in) {
           while ($buff = fread($in, 4096))
            fwrite($out, $buff);
          } else
           die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');

          fclose($in);
          fclose($out);
         } else
          die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }
        // Return JSON-RPC response
        die('{"jsonrpc" : "2.0", "result" : null, "id" : "id","prid",'.$prid.'}');

      }
      
}
